package com.mt.vsphere.core.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class JsonUtil {
    private static ObjectMapper objectMapper;
    static {
        objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }


    public static String getJsonString(Object o){
        try {

            return objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            return "";
        }
    }
    public static String getJsonStringAsUrlEncode(Object o){
        try {
            return URLEncoder.encode(objectMapper.writeValueAsString(o),"utf-8");
        } catch (JsonProcessingException e) {
            return "";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static <T> T getObjByJsonString(String jsonstr, Class<T> cls) {
        try {
            return objectMapper.readValue(jsonstr,cls);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static <T> List<T>  getListByJsonString(String jsonstr, Class<T> cls) {
        try {
            JavaType javaType = getCollectionType(ArrayList.class,cls);
            return objectMapper.readValue(jsonstr,javaType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static JavaType getCollectionType(Class<?> collectionClass, Class<?> elementClass){
        return objectMapper.getTypeFactory().constructCollectionLikeType(collectionClass, elementClass);
    }
}
